
#import "WorkGroupViewController.h"

#import "ChatController.h"

#import "GroupModel.h"

#import "FriendListCell.h"
#import "UIImageView+EMWebCache.h"

@interface WorkGroupViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchDisplayDelegate>

@property (nonatomic, strong) UITableView    * customerTableView;

@property (nonatomic, strong) NSMutableArray * dataSource;
/**装载群名称用来搜索*/
@property (nonatomic, strong) NSMutableArray * groupNameArray;

/**搜索结果数组*/
@property (nonatomic, strong) NSMutableArray * resultArray;

@property (nonatomic, strong) UISearchBar    * searchBar;

@property (nonatomic, strong) UISearchDisplayController * searchController;

@end

@implementation WorkGroupViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _dataSource = [NSMutableArray array];
        _resultArray = [NSMutableArray array];
        _groupNameArray = [NSMutableArray array];
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //self.view.backgroundColor = [UIColor redColor];
    // Do any additional setup after loading the view.
    [self requestForGroupData];
    [self creatUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    [self requestForGroupData];

}

- (void)requestForGroupData {
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    User *user = [User sharedUser];
    
    NSDictionary *parameters = @{@"type":@"1",@"employee_id":user.employee_id};
    NSLog(@"%@",parameters);
    [manager GetWithParameters:parameters method:@"search.hxuser.gounp.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"工作群的dictonary :%@",[dictionary description]);
        
        [_dataSource removeAllObjects];
        [_groupNameArray removeAllObjects];
        if ([[dictionary objectForKey:@"verification"]intValue] == 1)
        {
            for (NSDictionary *dataDic in dictionary[@"data"]) {
                
                GroupModel * groupModel = [[GroupModel alloc]init];
                [groupModel setValuesForKeysWithDictionary:dataDic];
                
                [_dataSource addObject:groupModel];
                
                [_groupNameArray addObject:groupModel.group_name];
                
            }
            [_customerTableView reloadData];
    
        }
        else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
    }];
    
}

- (void)creatUI
{
    //搜索框
    //_searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, SCREEN_W, 44)];
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 44)];
    
    _searchBar.placeholder = @"搜索";
    
    //_searchBar.backgroundColor = [UIColor greenColor];
    
    //搜索结果展示
    // 用 searchbar 初始化 SearchDisplayController
    // 并把 searchDisplayController 和当前 controller 关联起来
    _searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    
    _searchController.delegate = self;
    // searchResultsDataSource 就是 UITableViewDataSource
    _searchController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    _searchController.searchResultsDelegate = self;
    
    //主界面数据展示
    // _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_searchBar.frame), SCREEN_W, SCREEN_H-64-44) style:UITableViewStyleGrouped];
    _customerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    
    
    _customerTableView.backgroundColor = [UIColor whiteColor];
    _customerTableView.dataSource=self;
    _customerTableView.delegate=self;
    
    UINib * nib = [UINib nibWithNibName:@"FriendListCell" bundle:nil];
    
    [_customerTableView registerNib:nib forCellReuseIdentifier:@"ListCell"];
    
    _customerTableView.tableHeaderView = _searchBar;
    _customerTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    [self.view addSubview:_customerTableView];
    
    
}

#pragma mark - ---------------------------Search Delegate----------------------------

//只要用户在searchbar中输入内容就会触发该方法
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    //每次搜索之前，清空searchResults
    [_resultArray removeAllObjects];
    NSLog(@"%@", searchString);
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",searchString];//用于过滤
    _resultArray = [NSMutableArray arrayWithArray:[_groupNameArray filteredArrayUsingPredicate:predicate]];
    
    return YES;
}


#pragma mark- ------------------------UITableView 代理实现--------------------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//设置rows的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView != _customerTableView)
    {
        return [_resultArray count];
    }
    else
        return [_dataSource count];
}


//Cell的相关设置
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell * cell;
    if(tableView != _customerTableView){
        
        static NSString * cellName=@"cell";
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if(cell==nil)
        {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellName];
        }

        
        //cell.imageView.image = [UIImage imageNamed:@"group_header"];
        cell.textLabel.text = [_resultArray objectAtIndex:indexPath.row];
    }else{
        
        FriendListCell *cell;
        cell = (FriendListCell *)[tableView dequeueReusableCellWithIdentifier:@"ListCell"];
        if (cell == nil) {
            cell = [[FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FriendListCell"];
        }

        
//        GroupModel *groupModel = [_dataSource objectAtIndex:indexPath.row];
//        
//        cell.iconImageView.image = [UIImage imageNamed:@"group_header"];
        GroupModel *groupModel = [_dataSource objectAtIndex:indexPath.row];
        
        [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:groupModel.workgroup_img]  placeholderImage: [UIImage imageNamed:@"group_header"]];
        cell.friendNameLabel.text = groupModel.group_name;
        //cell.textLabel.text= [_groupNameArray objectAtIndex:indexPath.row];
        
        return cell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (tableView != _customerTableView) {
        for (GroupModel *groupModel in _dataSource) {
            if ([_resultArray[indexPath.row] isEqualToString:groupModel.group_name]) {
                ChatController *chatVC = [[ChatController alloc] initWithChatter:groupModel.group_id isGroup:YES];
                chatVC.title = groupModel.group_name;
                chatVC.groupID = groupModel.group_id;
                chatVC.groupType = WorkGroup;
                [self.navigationController pushViewController:chatVC animated:YES];
            }
        }
    }
    else {
        GroupModel *groupModel = [_dataSource objectAtIndex:indexPath.row];
        
        ChatController *chatController = [[ChatController alloc] initWithChatter:groupModel.group_id isGroup:YES];
        
        chatController.title = groupModel.group_name;
        chatController.groupID = groupModel.group_id;
        chatController.groupType = WorkGroup;
        [self.navigationController pushViewController:chatController animated:YES];
        //    [self.navigationControllerpopToRootViewControllerAnimated:YES];
    }
}


//设置section的title
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(tableView != _customerTableView){
        return @"搜索结果";
    }
    else{
        
        //return [NSString stringWithFormat:@"%c",97+section];
        return nil;
    }
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


@end

